﻿Imports System.Data.SqlClient
Imports CodeMatrix.Context
Imports System.Linq
Imports System.Data

Partial Class Apps_Shares_UcChangePassword
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim ctx = New DataClassesDataContext()
            Try
                If Request.QueryString("scid") Is Nothing Then
                    txtStaffNo.Text = HttpContext.Current.Session("Staff_no")
                Else
                    Dim staff = ctx.staffs.SingleOrDefault(Function(f) f.staff_code = Convert.ToInt32(Request.QueryString("scid")))
                    txtStaffNo.Text = staff.staff_no
                End If

                If Convert.ToInt32(Request.QueryString("pop")) = 1 Then
                    btnAbort.OnClientClick = "self.close();"
                Else
                    btnAbort.PostBackUrl = HttpContext.Current.Request.UrlReferrer.PathAndQuery
                End If

            Catch ex As Exception
                GenericHelper.ShowAlert(Me, ex)
            End Try
        End If
    End Sub

    Protected Sub OldPassword_Validated(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        Try
            args.IsValid = False

            Dim dt As DataTable = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                "SELECT staff_code, staff_no, staff_password, staff_password_salt " & _
                "FROM staff s " & _
                "WHERE staff_no=@staff_no", New SqlParameter("@staff_no", txtStaffNo.Text))

            If dt.Rows.Count > 0 Then

                Dim encryptedPassword_l1 As String = ""
                Dim encryptedPassword_l2 As String = dt.Rows(0)("staff_password")
                Dim saltValue As String = dt.Rows(0)("staff_password_salt")
                Dim passPhrase = saltValue.Substring(0, 8)

                Dim rijndaelKey As New CodeMatrix.Utilities.RijndaelEnhanced(passPhrase, saltValue, 4, 8, 128, "SHA1", saltValue)
                encryptedPassword_l1 = rijndaelKey.Decrypt(encryptedPassword_l2)

                If (Convert.ToBase64String(New System.Text.UnicodeEncoding().GetBytes(txtOldPassword.Text)) = encryptedPassword_l1) Then
                    args.IsValid = True
                Else
                    Throw New Exception("รหัสผ่านเก่าไม่ถูกต้อง")
                End If

            Else
                Throw New Exception("ไม่พบผู้ใช้งานนี้")
            End If

        Catch ex As Exception
            args.IsValid = False
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try
    End Sub

    Protected Sub NewPassword_Validated(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        Try
            If OldPasswordValidator.IsValid Then
                Dim reg As New System.Text.RegularExpressions.Regex("^.*(?=.{8,10})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+=\-,./\|{}\[\]]).*$")
                If reg.IsMatch(txtNewPassword.Text) = True Then

                    ' Did you use this password?
                    Dim staff_code As Int32
                    If Request.QueryString("scid") Is Nothing Then
                        staff_code = HttpContext.Current.Session("staff_code")
                    Else
                        staff_code = Convert.ToInt32(Request.QueryString("scid"))
                    End If
                    Dim dt As DataTable = CodeMatrix.Utilities.CodeHelper.GetDataTable( _
                    "SELECT TOP 3 staff_code,[password] staff_password,[password_salt] staff_password_salt " & _
                    "FROM log_password " & _
                    "WHERE staff_code=@staff_code " & _
                    "ORDER BY create_datetime DESC", New SqlParameter("@staff_code", staff_code))

                    If dt.Rows.Count > 0 Then
                        For Each r In dt.Rows
                            Dim encryptedPassword_l1 As String = ""
                            Dim encryptedPassword_l2 As String = r("staff_password")
                            Dim saltValue As String = r("staff_password_salt")
                            Dim passPhrase = saltValue.Substring(0, 8)

                            Dim rijndaelKey As New CodeMatrix.Utilities.RijndaelEnhanced(passPhrase, saltValue, 4, 8, 128, "SHA1", saltValue)
                            encryptedPassword_l1 = rijndaelKey.Decrypt(encryptedPassword_l2)

                            If (Convert.ToBase64String(New System.Text.UnicodeEncoding().GetBytes(txtNewPassword.Text)) = encryptedPassword_l1) Then
                                Throw New Exception("รหัสผ่านนี้ถูกใช้ไปแล้ว")
                            Else
                                args.IsValid = True
                            End If
                        Next
                    End If
                    args.IsValid = True
                Else
                    Throw New Exception("รหัสผ่านใหม่จะต้องมีจำนวนตัวอักษรไม่น้อยกว่า 8 และไม่เกิน 10 ตัวอักษร " & Constants.vbCrLf & "สำหรับอักขระต้องมี ตัวหนังสือ ตัวเลข และอักขรพิเศษ")
                End If
            End If
        Catch ex As Exception
            args.IsValid = False
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try
    End Sub

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Try

            If OldPasswordValidator.IsValid And NewPasswordValidator.IsValid Then

                ' Pass all validation so 
                ' 1. update new password 
                ' 2. update staff_status_login = 0
                ' 3. keep the old one in log_password

                Dim ctx As DataClassesDataContext = New DataClassesDataContext
                Dim popUpWindow As Int32 = Convert.ToInt32(Request.QueryString("pop"))
                Dim staff_code As Int32
                If Request.QueryString("scid") Is Nothing Then
                    staff_code = HttpContext.Current.Session("staff_code")
                Else
                    staff_code = Convert.ToInt32(Request.QueryString("scid"))
                End If

                Dim saltValue As String = System.Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16)
                Dim encryptedPassword_l1 As String = Convert.ToBase64String(New System.Text.UnicodeEncoding().GetBytes(txtNewPassword.Text))
                Dim encryptedPassword_l2 As String = ""
                Dim passPhrase = saltValue.Substring(0, 8)

                Dim rijndaelKey As New CodeMatrix.Utilities.RijndaelEnhanced(passPhrase, saltValue, 4, 8, 128, "SHA1", saltValue)
                encryptedPassword_l2 = rijndaelKey.Encrypt(encryptedPassword_l1)

                CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery( _
                "UPDATE staff SET staff_password = @staff_password, staff_password_salt = @staff_password_salt, staff_status_login = 0 WHERE staff_code = @staff_code", _
                New SqlParameter("@staff_code", staff_code), _
                New SqlParameter("@staff_password", encryptedPassword_l2), _
                New SqlParameter("@staff_password_salt", saltValue))

                CodeMatrix.Utilities.CodeHelper.ExecuteNonQuery( _
                "INSERT INTO log_password (staff_code,[password],[password_salt],[staff_code_create] ,[create_datetime]) " & _
                "VALUES (@staff_code, @staff_password, @staff_password_salt, @staff_code_create, @create_datetime)", _
                New SqlParameter("@staff_code", staff_code), _
                New SqlParameter("@staff_password", encryptedPassword_l2), _
                New SqlParameter("@staff_password_salt", saltValue), _
                New SqlParameter("@staff_code_create", Session("staff_code")), _
                New SqlParameter("@create_datetime", Date.Now))


                GenericHelper.ShowAlert(Me, "ข้อมูลถูกบันทึกเรียบร้อยแล้ว")
                Dim staff_no = ctx.staffs.SingleOrDefault(Function(f) f.staff_code = staff_code).staff_no
                CodeMatrix.Business.GenericData.WriteLog("ผู้ใช้งาน " & HttpContext.Current.Session("staff_no") & " เปลี่ยนรหัสผ่านผู้ใช้งาน " & staff_no & " เรียบร้อยแล้ว", 13, "U", staff_code)
                If popUpWindow = 1 Then
                    ScriptManager.RegisterStartupScript(Me, _
                                                        Me.GetType(), _
                                                        Guid.NewGuid().ToString(), _
                                                        "self.close();", _
                                                        True _
                                                        )
                Else
                    ScriptManager.RegisterStartupScript(Me, _
                                                        Me.GetType(), _
                                                        Guid.NewGuid().ToString(), _
                                                        "window.location = 'welcome.aspx';", _
                                                        True _
                                                        )
                End If

            End If

        Catch ex As Exception
            GenericHelper.ShowAlert(Me, ex.Message)
        End Try
    End Sub
End Class
